import re
import serial
import time

# 读取信息并匹配
def serial_send_2_recv_re_match(ser:serial.Serial,  # 串口句柄
                                send_str:str,           # 发送数据
                                exStr:str=r'',
                                time_out = 0.2,      # 默认为0.2s
                                max_time = 3,
                                get_flag = False,    # 如果要获取值，请开启这个，如果是单纯的匹配值，则不需要开启
                                post_exStr = '',     # 后置匹配，如果get_flag不开启，则不起作用
                                get_min_length = 0      # 最好提前传递获取数值的最小长度，好进行匹配(有问题)
                                ):             # 匹配数据
    mask = None
    length = len(exStr)
    exlength = length + get_min_length + len(post_exStr)
    try:
        if exStr:
            if get_flag:
                exStr += '(.*)'
                if post_exStr != '':
                    exStr += post_exStr
            mask = re.compile(exStr)

        print('发送数据')
        ser.write(send_str.encode())
        ser.write_timeout = time_out        # 重新设置超时时间
        print('发送数据成功')

        start_time = time.time()
        # print(time.time() - start_time)
        data = ''
        while time.time() - start_time < max_time:      # 做了最大停顿时间的处理
            temp = ser.read(1)
            if temp != b'':
                data += temp.decode()
            else:
                # print('接收数据', data, temp)
                if exStr and len(data) >= exlength and temp == b'':
                    # print('jj',data)
                    match_list = mask.findall(data)
                    if match_list:
                        print('检查接收到的数据：',data, match_list)
                        return True, match_list[0]      # 返回匹配成功，和匹配的值
                    else:
                        return False, None        # 匹配失败
                else:
                    print('检查为接收到数据的时间，未接收到数据')
    except Exception as e:
        print('发送指令失败，报错',e)
        return False,None       # 报错
    print('意外')
    return False, None  # 超时或者意外情况
